﻿using Inovout.Component;
using Inovout.Data.Service;
using Inovout.Organization.Domain;
using Inovout.People.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Inovout.Cloud.Messager.WebPage.Models
{
    public class EmployeeLogic : RepositoryService<Employee>
    {
        DepartmentLogic departmentlogic = new DepartmentLogic();
        PersonLogic personlogic = new PersonLogic();
        IRepositoryService<Employee> Service = ComponentRegistry.Resolve<IRepositoryService<Employee>>();

        public void HandleEmployee()
        {
            List<Person> persons = personlogic.GetAllPerson();
            List<Employee> Emloyees = GetAllEmployee();

            foreach (Person person in persons)
            {
                if (Emloyees.Count() == 0)
                {
                    OrganizationUnit department = departmentlogic.GetDepaetment(person.OrganizationUnitId);
                    Employee employee = new Employee();
                    if (department != null)
                    {
                        employee.Person = person;
                        employee.Organization = department;
                    }
                    InsertEmployee(employee);
                }
                else
                {
                    Employee employee = Emloyees.Where(c => c.Person.Name == person.Name).Select(c => c).SingleOrDefault();
                    if (employee == null)
                    {
                        employee = new Employee();
                        OrganizationUnit department = departmentlogic.GetDepaetment(person.OrganizationUnitId);
                        if (department != null)
                        {
                            employee.Person = person;
                            employee.Organization = department;
                        }
                        InsertEmployee(employee);
                    }
                    else
                    {
                        Emloyees.Remove(employee);
                        OrganizationUnit department = departmentlogic.GetDepaetment(person.OrganizationUnitId);
                        employee.Organization = department;
                        Service.Save(employee);
                    }
                }
            }
            RemoveEmployee(Emloyees);

        }
        public void InsertEmployee(Employee employee)
        {
            Service.Save(employee);
        }
        public void RemoveEmployee(List<Employee> employess)
        {
            foreach (Employee employee in employess)
            {
                Service.Delete(employee);
            }
        }
        public List<Employee> GetAllEmployee()
        {
            return Service.Query().ToList();
        }
    }
}